﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using HslCommunication;
using HslCommunication.Profinet.Melsec;


namespace Tool
{
   public class PLCCommunicate
    {
       
     public  MelsecMcNet melsecMC;

        /// <summary>
        /// 连接PLC
        /// </summary>
        /// <param name="ip"></param>
        /// <param name="port"></param>
        public bool ConnectPLC(string ip, int port)
        {
            if (melsecMC == null)
            {
                melsecMC = new MelsecMcNet(ip, port);
                melsecMC.ConnectTimeOut = 2000;
                melsecMC.ConnectClose();
                melsecMC.ConnectServer();
                OperateResult connect = melsecMC.ConnectServer();
                return connect.IsSuccess;

            }
            else
            {
                melsecMC.ConnectClose();
                OperateResult connect = melsecMC.ConnectServer();
                return connect.IsSuccess;   
            }

        }

        public void DisConnect()
        {
            try
            {
                melsecMC.ConnectClose();
            }
            catch (Exception)
            {

                throw;
            }
        }

        public short Read(string address)
        {
            short value = melsecMC.ReadInt16(address).Content;
            return value;
        }

        public bool Write(string address, short value)
        {
            OperateResult res = melsecMC.Write(address,value);
            if (res.IsSuccess)
            {
                return true;
            }
            else
            {
                return false;
            }
        }
    }
}
